<template>
    <view>
        <view
            class="flex align-center justify-between padding-top-30 padding-lr-30"
        >
            <view class="text-26">共 {{ allNum }} 件宝贝</view>
            <view
                class="text-26"
                @click="is_guan == 1 ? (is_guan = 2) : (is_guan = 1)"
                >{{ is_guan == 1 ? "管理" : "完成" }}</view
            >
        </view>
        <view class="out">
            <view
                class="card"
                v-for="(item, index) in list"
                @click.stop="
                    jump('/dabai/pages/aShop/aShop?id=' + item[0].shop_id)
                "
                :key="index"
            >
                <view class="u-flex" style="margin-bottom: 20rpx">
                    <view class="square" @click.stop="onShopChoose(index)">
                        <image
                            :src="BaseUrl + '/static/yCreate/successful.png'"
                            v-if="item.every((item) => item.checked)"
                            class="sign"
                            mode="widthFix"
                        >
                        </image>
                    </view>
                    <view class="shop-message u-flex">
                        <view>{{ item[0].shop_name }}</view>
                    </view>
                    <u-icon name="arrow-right"></u-icon>
                </view>
                <u-swipe-action
                    :show="_item.showOptions"
                    :index="_index"
                    v-for="(_item, _index) in item"
                    @click="clickDel(item, _index)"
                    @open="open(_item)"
                    :options="options"
                    :key="_index"
                >
                    <view class="u-flex-center">
                        <view
                            class="square"
                            @click="onGoodsChoose(item, index, _index)"
                        >
                            <image
                                :src="
                                    BaseUrl + '/static/yCreate/successful.png'
                                "
                                v-if="_item.checked"
                                class="sign"
                                mode="widthFix"
                            >
                            </image>
                        </view>
                        <view
                            class="title-wrap u-flex u-col-top"
                            style="width: 100%"
                            @click.stop="
                                jump(
                                    '/pages/product/goods?id=' + _item.goods_id
                                )
                            "
                        >
                            <image
                                :src="BaseUrl + _item.image"
                                mode="aspectFill"
                                class="goods-img"
                            ></image>
                            <view class="message" style="width: 100%">
                                <view class="u-line-2 text-cut-two">{{
                                    _item.title
                                }}</view>
                                <view class="cate"
                                    >规格：<text
                                        v-for="(__item, __index) in _item.sku
                                            .difference"
                                        :key="__index"
                                        >{{ __item + " " }}</text
                                    ></view
                                >
                                <view class="u-flex u-row-between u-m-t-30">
                                    <view class="price">
                                        <text>￥</text>
                                        {{
                                            vip_time !== null
                                                ? _item.sku.vip_price
                                                : _item.sku.price
                                        }}
                                    </view>
                                    <u-number-box
                                        v-model="_item.number"
                                        @minus="minus($event, _item)"
                                        @plus="plus($event, _item)"
                                        :input-width="50"
                                        :input-height="50"
                                        :min="1"
                                        @click.native.stop
                                        @change.native="
                                            valChange($event, _item)
                                        "
                                    ></u-number-box>
                                </view>
                            </view>
                        </view>
                    </view>
                </u-swipe-action>
            </view>
        </view>
        <view class="placeholder"></view
        ><!-- 防止内容塌陷 -->
        <view class="btn-box">
            <view class="u-flex u-row-between" style="width: 100%">
                <view class="u-flex">
                    <view class="square" @click="onAllChoose">
                        <image
                            v-if="isAllChoose"
                            :src="BaseUrl + '/static/yCreate/successful.png'"
                            class="sign"
                            mode="widthFix"
                        >
                        </image>
                    </view>
                    <view>全选</view>
                </view>
                <view class="u-flex-center">
                    <view
                        class="u-flex-col u-col-bottom u-m-r-30"
                        v-if="is_guan == 1"
                    >
                        <view class="u-flex">
                            <view class="total">合计：</view>
                            <view class="price"
                                ><text>￥</text>{{ totalPrice }}</view
                            >
                        </view>
                    </view>
                    <view
                        class="btn u-flex-center"
                        v-if="is_guan == 1"
                        @tap="$u.throttle(submit, 1500)"
                        >结算({{ chooseList.length }})</view
                    >
                    <view
                        class="delbtn"
                        @click="del(list, chooseList)"
                        v-if="is_guan == 2"
                        >删除</view
                    >
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { BaseUrl } from "../../utils/req.js";
export default {
    data() {
        return {
            BaseUrl,
            isAllChoose: false,
            isEdit: false, //编辑状态
            list: [],
            chooseList: [],
            subList: [],
            options: [
                {
                    text: "删除",
                    style: {
                        backgroundColor: "#dd524d",
                    },
                },
            ],
            is_guan: 1,
            allNum: 0,
            totalPrice: 0, //总价
            checked: false,
            allShopsChecked: false, // 所有店铺是否全选的状态，默认为未全选
            isLoading: false, // 添加一个加载状态
            getListDebounced: null, // 用于存储防抖后的getList函数
            vip_time: null,
        };
    },
    watch: {
        list: {
            handler(newVal) {
                this.onCalculation();
            },
            deep: true,
        },
    },
    onLoad() {
        this.vip_time = uni.getStorageSync("userInfo").vip_time;
    },
    onShow() {
        this.isAllChoose = false;
        (this.isAll = false),
            (this.chooseList = []),
            (this.subList = []),
            this.getList();
    },
    computed: {},
    methods: {
        /**
         * 选择店铺
         */
        onShopChoose(index) {
            this.list[index].forEach((item) => {
                item.checked = !this.allShopsChecked;
            });
            this.allShopsChecked = !this.allShopsChecked;
            this.$set(this.list, index, this.list[index]);
            this.onCalculation();
        },
        /**
         * 选择商品
         */
        onGoodsChoose(item, index, subIdx) {
            // 切换当前商品的选中状态
            this.list[index][subIdx].checked =
                !this.list[index][subIdx].checked;

            // 重新评估当前店铺的全选状态
            const allCheckedInShop = this.list[index].every(
                (item) => item.checked
            );

            // 更新店铺的全选状态
            if ("shop_checked" in this.list[index]) {
                this.list[index].shop_checked = allCheckedInShop;
            }

            // 更新全局店铺全选状态
            this.allShopsChecked = this.list.every((shop) =>
                shop.every((item) => item.checked)
            );

            // 强制更新
            this.$set(this.list, index, this.list.slice(index, index + 1)[0]);
            this.onCalculation();
        },
        /**
         * 全选
         */
        onAllChoose() {
            this.chooseList = [];
            this.isAllChoose = !this.isAllChoose;
            //全选
            this.list.forEach((item) => {
                item.forEach((item) => {
                    item.checked = this.isAllChoose;
                    if (this.isAllChoose == true) {
                        this.chooseList.push({
                            goods_id: item.goods_id,
                            number: item.number,
                            sku_id: item.sku_id,
                        });
                    }
                });
                item.checked = this.isAllChoose;
            });
            this.$set(this.list);
            this.onCalculation();
        },
        /**
         * 计算是否全选
         */
        onCalculation() {
            let total = 0;
            let choose = 0;
            this.chooseList = [];
            let price = 0.0;
            this.list.forEach((item) => {
                total++;
                item.forEach((_item) => {
                    choose++;
                    if (_item.checked == true) {
                        if (this.vip_time) {
                            price += Number(_item.sku.vip_price * _item.number);
                            this.chooseList.push({
                                goods_id: _item.goods_id,
                                number: _item.number,
                                sku_id: _item.sku_id,
                            });
                        } else {
                            price += Number(_item.sum);
                            this.chooseList.push({
                                goods_id: _item.goods_id,
                                number: _item.number,
                                sku_id: _item.sku_id,
                            });
                        }
                    }
                });
            });
            this.totalPrice = price.toFixed(2);
            this.isAllChoose = choose === this.chooseList.length;
        },
        //获取数据
        getList() {
            if (this.isLoading) return; // 如果正在加载，则直接返回，避免重复请求
            this.isLoading = true; // 开始加载，设置锁
            //更新购物车的时候存储的状态
            const selectedItemsBeforeUpdate = this.list.reduce((acc, shop) => {
                return acc.concat(shop.filter((item) => item.checked));
            }, []);
            this.$request
                .post("api/wanlshop.cart/synchros", { cart: [] })
                .then((res) => {
                    let allNum = 0;
                    /**
                     * 更新购物车条数
                     */
                    res.data.forEach((item) => {
                        item.forEach((item) => {
                            allNum++;
                            this.$set(item, "showOptions", false);
                        });
                    });
                    // 优化同步逻辑，直接基于ID匹配而非索引
                    res.data.forEach((newShop) => {
                        const oldShop = this.list.find(
                            (oldS) => oldS[0].shop_id === newShop[0].shop_id
                        );
                        if (oldShop) {
                            newShop.forEach((newItem) => {
                                const oldItem = oldShop.find(
                                    (oldI) =>
                                        oldI.goods_id === newItem.goods_id &&
                                        oldI.sku_id === newItem.sku_id
                                );
                                if (oldItem && oldItem.checked) {
                                    newItem.checked = true;
                                }
                            });
                        }
                    });
                    this.onCalculation();
                    this.list = res.data;
                    this.allNum = allNum;
                    this.isLoading = false; // 请求结束，释放锁
                });
        },
        //步进器减
        minus(a, e) {
            this.$u
                .post("/api/wanlshop.cart/storage", {
                    goods_id: e.goods_id,
                    number: e.number,
                    sku_id: e.sku_id,
                    sum: e.sum,
                    type: "bcsub",
                })
                .then((res) => {
                    if (res.code == 1) {
                        e.sum = Number(e.sku.price) * a.value;
                        this.getList();
                    } else {
                        this.$u.toast(res.msg);
                    }
                });
        },
        //步进器加
        plus(a, e) {
            this.$u
                .post("/api/wanlshop.cart/storage", {
                    goods_id: e.goods_id,
                    number: e.number,
                    sku_id: e.sku_id,
                    sum: e.sum,
                    type: "bcadd",
                })
                .then((res) => {
                    if (res.code == 1) {
                        e.sum = Number(e.sku.price) * a.value;
                        this.getList();
                    } else {
                        this.$u.toast(res.msg);
                    }
                });
        },
        /**
         * 步进器输入
         */
        valChange(e, item) {
            this.$u
                .post("/api/wanlshop.cart/storage", {
                    goods_id: item.goods_id,
                    number: item.number,
                    sku_id: item.sku_id,
                    sum: item.sum,
                    type: "bcadd",
                })
                .then((res) => {
                    if (res.code == 1) {
                        item.sum =
                            Number(item.sku.price) * e.detail.__args__[0].value;
                        this.getList();
                    } else {
                        this.$u.toast(res.msg);
                    }
                });
        },
        // 将createThrottle定义为methods的一个方法
        createThrottle(func, wait) {
            let last = 0;
            return function (...args) {
                const now = Date.now();
                if (now - last > wait) {
                    last = now;
                    func.apply(this, args);
                }
            };
        },

        // 结算
        submit() {
            if (this.chooseList.length > 0) {
                this.jump(
                    "/liu/pages/confirmOrder?ids=" +
                        JSON.stringify(this.chooseList) +
                        "&subList=" +
                        JSON.stringify(this.subList)
                );
            } else {
                this.$u.toast("请选择商品后点击结算");
            }
        },
        //跳转路径
        jump(url) {
            uni.navigateTo({
                url: url,
            });
        },
        //左滑删除
        clickDel(item, index) {
            let isItem = [
                {
                    goods_id: item[index].goods_id,
                    number: item[index].number,
                    sku_id: item[index].sku_id,
                },
            ];
            uni.showModal({
                title: "提示",
                content: "确认删除吗？",
                showCancel: true,
                success: ({ confirm, cancel }) => {
                    if (confirm) {
                        this.$u
                            .post("/api/wanlshop.cart/storage", {
                                data: isItem,
                                type: "del",
                            })
                            .then((res) => {
                                if (res.code == 1) {
                                    uni.showToast({
                                        title: res.msg,
                                        icon: "none",
                                    });

                                    setTimeout(() => {
                                        this.getList();
                                    }, 1000);
                                } else {
                                    uni.showToast({
                                        title: res.msg,
                                        icon: "none",
                                    });
                                }
                            });
                    }
                },
            });
        },
        //单选删除
        del(item, index) {
            uni.showModal({
                title: "提示",
                content: "确认删除吗？",
                showCancel: true,
                success: ({ confirm, cancel }) => {
                    if (confirm) {
                        this.$u
                            .post("/api/wanlshop.cart/storage", {
                                data: index,
                                type: "del",
                            })
                            .then((res) => {
                                if (res.code == 1) {
                                    uni.showToast({
                                        title: res.msg,
                                        icon: "none",
                                    });
                                    setTimeout(() => {
                                        this.getList();
                                    }, 1000);
                                } else {
                                    uni.showToast({
                                        title: res.msg,
                                        icon: "none",
                                    });
                                }
                            });
                    }
                },
            });
        },
        //作画打开删除
        open(item) {
            this.list.map((val, idx) => {
                val.map((val2) => {
                    val2.showOptions = false;
                });
            });
            item.showOptions = true;
        },
        //防抖
    },
    // 在created中使用
    created() {
        this.getListDebounced = this.createThrottle(this.getList, 1000);
    },
    mounted() {},
};
</script>
<style>
page {
    background-color: #f7f7f7;
}
</style>
<style lang="scss">
@import url(@/components/common.css);
.price {
    font-size: 40rpx !important;
    color: #eb5c20;
    text {
        font-weight: 500;
        font-size: 20rpx;
    }
}
.square {
    flex-shrink: 0;
    width: 40rpx;
    height: 40rpx;
    position: relative;
    margin-right: 25rpx;
    border: 1rpx solid #dcdcdc;
    border-radius: 50%;

    image {
        width: 38rpx;
        height: auto;
        position: absolute;
        bottom: 0rpx;
    }
}

.out {
    padding: 20rpx;
    .edit-btn {
        width: 128rpx;
        height: 48rpx;
        border-radius: 50rpx;
        background: linear-gradient(90deg, #00a67a, #057748);
        font-size: 24rpx;
        color: #ffffff;
    }

    .card {
        margin-top: 30rpx;
        padding: 30rpx;
        background: #ffffff;
        .card-item {
            padding-top: 30rpx;
            &:not(:last-child) {
                padding-bottom: 30rpx;
                border-bottom: 1rpx solid #dfdfdf;
            }
        }
        .shop-message {
            font-size: 32rpx;
            font-weight: 550;
            .standing {
                margin-left: 18rpx;
                width: 64rpx;
                height: 32rpx;
                background: #f43000;
                border-radius: 4rpx;
                font-size: 24rpx;
                color: #ffffff;
            }
            .standing2 {
                background: #606dce;
            }
        }
        .right-icon {
            width: 12rpx;
            height: auto;
        }
        .goods-img {
            margin-left: 15rpx;
            width: 180rpx;
            height: 180rpx;
            border-radius: 10rpx;
            flex-shrink: 0;
        }

        .message {
            margin-left: 36rpx;
            .cate {
                width: fit-content;
                width: -webkit-fit-content;
                width: -moz-fit-content;
                padding: 3rpx;
                background: #fafafa;
                font-size: 22rpx;
                border-radius: 5rpx;
                margin-top: 15rpx;
            }
            view {
                font-size: 28rpx;
            }
        }
    }
}

.placeholder {
    width: 100%;
    height: 174rpx;
}

.btn-box {
    position: fixed;
    bottom: 0;
    padding: 8rpx 34rpx 0 41rpx;
    width: 100%;
    height: 144rpx;
    background: #ffffff;
    box-shadow: 0rpx 1rpx 0rpx 0rpx #e7e7e7;
    border-radius: 10rpx;
    .total {
        font-size: 24rpx;
        color: #222;
    }

    .message {
        font-size: 24rpx;
        color: #888888;
    }
    .btn {
        width: 210rpx;
        height: 79rpx;
        background: linear-gradient(90deg, #00a67a, #057748);
        border-radius: 45rpx;
        font-size: 32rpx;
        color: #ffffff;
    }
}
.delbtn {
    width: 180rpx;
    height: 72rpx;
    background: #fff;
    border-radius: 36rpx;
    border: 1px solid #057748;
    font-size: 32rpx;
    color: #057748;
    line-height: 72rpx;
    text-align: center;
}
/deep/.u-swipe-content {
    margin-bottom: 30rpx;
}
</style>
